#include "../include/forgotpasswordwidget.h"
#include "../include/config.h"
#include <QRegularExpression>
#include <QCheckBox>

ForgotPasswordWidget::ForgotPasswordWidget(AuthService *authService, QWidget *parent)
    : QWidget(parent)
    , m_authService(authService)
    , m_primaryColor("#4A90E2")
    , m_secondaryColor("#7ED321")
    , m_backgroundColor("#2C3E50")
    , m_textColor("#ECF0F1")
    , m_errorColor("#E74C3C")
    , m_successColor("#27AE60")
    , m_warningColor("#F39C12")
{
    setupUI();
    applyStyles();

    connect(m_authService, &AuthService::forgotPasswordSucceeded,
            this, &ForgotPasswordWidget::onForgotPasswordSucceeded);
    connect(m_authService, &AuthService::forgotPasswordFailed,
            this, &ForgotPasswordWidget::onForgotPasswordFailed);
    connect(m_authService, &AuthService::resetPasswordSucceeded,
            this, &ForgotPasswordWidget::onResetPasswordSucceeded);
    connect(m_authService, &AuthService::resetPasswordFailed,
            this, &ForgotPasswordWidget::onResetPasswordFailed);
}

ForgotPasswordWidget::~ForgotPasswordWidget()
{
    // 所有UI组件通过Qt的父子关系自动管理
}

void ForgotPasswordWidget::setupUI()
{
    m_mainLayout = new QVBoxLayout(this);
    m_mainLayout->setSpacing(0);
    m_mainLayout->setContentsMargins(0, 0, 0, 0);

    // 确保窗口填满整个区域
    this->setContentsMargins(0, 0, 0, 0);

    // 创建主容器 - 使用居中卡片设计
    QWidget *mainContainer = new QWidget();
    mainContainer->setObjectName("forgotMainContainer");

    QHBoxLayout *containerLayout = new QHBoxLayout(mainContainer);
    containerLayout->setContentsMargins(0, 0, 0, 0);
    containerLayout->setSpacing(0);

    // 左侧空白区域 (15%)
    QWidget *leftSpacer = new QWidget();
    leftSpacer->setObjectName("spacerWidget");

    // 中央卡片 (70%)
    QWidget *centerCard = new QWidget();
    centerCard->setObjectName("forgotCard");
    centerCard->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);

    // 右侧空白区域 (15%)
    QWidget *rightSpacer = new QWidget();
    rightSpacer->setObjectName("spacerWidget");

    // 设置比例：左15% 中70% 右15%
    containerLayout->addWidget(leftSpacer, 3);
    containerLayout->addWidget(centerCard, 14);
    containerLayout->addWidget(rightSpacer, 3);

    // 设置忘记密码卡片内容
    setupForgotCard(centerCard);

    m_mainLayout->addWidget(mainContainer);
}

void ForgotPasswordWidget::setupForgotCard(QWidget *centerCard)
{
    QVBoxLayout *cardLayout = new QVBoxLayout(centerCard);
    cardLayout->setContentsMargins(0, 0, 0, 0);
    cardLayout->setSpacing(0);

    // 创建表单容器 (垂直居中)
    QWidget *formContainer = new QWidget();
    formContainer->setObjectName("forgotFormContainer");
    formContainer->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);

    QVBoxLayout *formLayout = new QVBoxLayout(formContainer);
    formLayout->setContentsMargins(30, 8, 30, 25); // 进一步减少顶部边距
    formLayout->setSpacing(18);

    // 重新设计的头部区域 - 左图标 + 中间文字 + 右装饰
    QWidget *headerWidget = new QWidget();
    QHBoxLayout *headerLayout = new QHBoxLayout(headerWidget);
    headerLayout->setSpacing(18);
    headerLayout->setContentsMargins(0, 0, 0, 0);

    // 左侧Logo图标 - 减小尺寸
    m_logoLabel = new QLabel();
    m_logoLabel->setText("🔑");
    m_logoLabel->setAlignment(Qt::AlignCenter);
    m_logoLabel->setObjectName("forgotLogo");
    m_logoLabel->setFixedSize(40, 40);
    headerLayout->addWidget(m_logoLabel);

    // 中间标题区域 - 居中对齐
    QWidget *titleWidget = new QWidget();
    QVBoxLayout *titleLayout = new QVBoxLayout(titleWidget);
    titleLayout->setSpacing(2);
    titleLayout->setContentsMargins(0, 0, 0, 0);

    m_titleLabel = new QLabel("找回密码");
    m_titleLabel->setAlignment(Qt::AlignCenter);
    m_titleLabel->setObjectName("forgotTitle");
    titleLayout->addWidget(m_titleLabel);

    QLabel *subtitle = new QLabel("请输入您的邮箱地址，我们将发送重置链接");
    subtitle->setAlignment(Qt::AlignCenter);
    subtitle->setObjectName("forgotSubtitle");
    subtitle->setWordWrap(true);
    titleLayout->addWidget(subtitle);

    headerLayout->addWidget(titleWidget, 1); // 给标题区域更多空间

    // 右侧装饰图标 - 减小尺寸
    QLabel *decorIcon = new QLabel();
    decorIcon->setText("🔐");
    decorIcon->setAlignment(Qt::AlignCenter);
    decorIcon->setObjectName("forgotDecorIcon");
    decorIcon->setFixedSize(40, 40);
    headerLayout->addWidget(decorIcon);

    formLayout->addWidget(headerWidget);

    // 堆叠窗口
    m_stackedWidget = new QStackedWidget();
    formLayout->addWidget(m_stackedWidget);

    // 创建邮箱验证页面
    setupEmailPage();

    // 创建重置密码页面
    setupResetPage();

    // 将表单容器垂直居中
    cardLayout->addStretch();
    cardLayout->addWidget(formContainer);
    cardLayout->addStretch();
}

void ForgotPasswordWidget::setupEmailPage()
{
    m_emailPage = new QWidget();
    QVBoxLayout *emailLayout = new QVBoxLayout(m_emailPage);
    emailLayout->setSpacing(15);

    // 说明文字
    m_instructionLabel = new QLabel("请输入您的邮箱地址，我们将发送重置密码的链接到您的邮箱", this);
    m_instructionLabel->setAlignment(Qt::AlignCenter);
    m_instructionLabel->setObjectName("instructionLabel");
    m_instructionLabel->setWordWrap(true);
    emailLayout->addWidget(m_instructionLabel);

    // 邮箱输入组
    m_emailGroup = new QGroupBox("邮箱验证", this);
    m_emailGroup->setObjectName("inputGroup");
    m_emailFormLayout = new QFormLayout(m_emailGroup);
    m_emailFormLayout->setSpacing(12);

    m_emailEdit = new QLineEdit(this);
    m_emailEdit->setPlaceholderText("请输入注册时使用的邮箱地址");
    m_emailEdit->setObjectName("inputField");
    connect(m_emailEdit, &QLineEdit::textChanged, this, &ForgotPasswordWidget::onEmailChanged);
    connect(m_emailEdit, &QLineEdit::returnPressed, this, &ForgotPasswordWidget::onSendResetEmailClicked);
    m_emailFormLayout->addRow("邮箱地址:", m_emailEdit);

    m_emailHintLabel = new QLabel(this);
    m_emailHintLabel->setObjectName("hintLabel");
    m_emailHintLabel->setWordWrap(true);
    m_emailFormLayout->addRow("", m_emailHintLabel);

    emailLayout->addWidget(m_emailGroup);

    // 按钮区域
    QVBoxLayout *emailButtonLayout = new QVBoxLayout();
    emailButtonLayout->setSpacing(10);

    m_sendEmailButton = new QPushButton("发送重置邮件", this);
    m_sendEmailButton->setObjectName("primaryButton");
    m_sendEmailButton->setDefault(true);
    connect(m_sendEmailButton, &QPushButton::clicked, this, &ForgotPasswordWidget::onSendResetEmailClicked);
    emailButtonLayout->addWidget(m_sendEmailButton);

    m_backToLoginButton1 = new QPushButton("返回登录", this);
    m_backToLoginButton1->setObjectName("linkButton");
    connect(m_backToLoginButton1, &QPushButton::clicked, this, &ForgotPasswordWidget::onBackToLoginClicked);
    emailButtonLayout->addWidget(m_backToLoginButton1);

    emailLayout->addLayout(emailButtonLayout);

    // 状态显示
    m_emailStatusLabel = new QLabel(this);
    m_emailStatusLabel->setAlignment(Qt::AlignCenter);
    m_emailStatusLabel->setObjectName("statusLabel");
    m_emailStatusLabel->setWordWrap(true);
    emailLayout->addWidget(m_emailStatusLabel);

    m_emailProgressBar = new QProgressBar(this);
    m_emailProgressBar->setVisible(false);
    m_emailProgressBar->setObjectName("progressBar");
    emailLayout->addWidget(m_emailProgressBar);

    m_stackedWidget->addWidget(m_emailPage);
}

void ForgotPasswordWidget::setupResetPage()
{
    m_resetPage = new QWidget();
    QVBoxLayout *resetLayout = new QVBoxLayout(m_resetPage);
    resetLayout->setSpacing(15);

    // 说明文字
    QLabel *resetInstructionLabel = new QLabel("请输入您收到的重置令牌和新密码", this);
    resetInstructionLabel->setAlignment(Qt::AlignCenter);
    resetInstructionLabel->setObjectName("instructionLabel");
    resetInstructionLabel->setWordWrap(true);
    resetLayout->addWidget(resetInstructionLabel);

    // 重置密码输入组
    m_resetGroup = new QGroupBox("重置密码", this);
    m_resetGroup->setObjectName("inputGroup");
    m_resetFormLayout = new QFormLayout(m_resetGroup);
    m_resetFormLayout->setSpacing(12);

    // 重置令牌输入
    m_tokenEdit = new QLineEdit(this);
    m_tokenEdit->setPlaceholderText("请输入邮件中的重置令牌");
    m_tokenEdit->setObjectName("inputField");
    connect(m_tokenEdit, &QLineEdit::textChanged, this, &ForgotPasswordWidget::onTokenChanged);
    m_resetFormLayout->addRow("重置令牌:", m_tokenEdit);

    m_tokenHintLabel = new QLabel(this);
    m_tokenHintLabel->setObjectName("hintLabel");
    m_tokenHintLabel->setWordWrap(true);
    m_resetFormLayout->addRow("", m_tokenHintLabel);

    // 新密码输入
    m_newPasswordEdit = new QLineEdit(this);
    m_newPasswordEdit->setEchoMode(QLineEdit::Password);
    m_newPasswordEdit->setPlaceholderText("请输入新密码");
    m_newPasswordEdit->setObjectName("inputField");
    connect(m_newPasswordEdit, &QLineEdit::textChanged, this, &ForgotPasswordWidget::onPasswordChanged);
    m_resetFormLayout->addRow("新密码:", m_newPasswordEdit);

    m_passwordHintLabel = new QLabel(this);
    m_passwordHintLabel->setObjectName("hintLabel");
    m_passwordHintLabel->setWordWrap(true);
    m_resetFormLayout->addRow("", m_passwordHintLabel);

    // 确认密码输入
    m_confirmPasswordEdit = new QLineEdit(this);
    m_confirmPasswordEdit->setEchoMode(QLineEdit::Password);
    m_confirmPasswordEdit->setPlaceholderText("请再次输入新密码");
    m_confirmPasswordEdit->setObjectName("inputField");
    connect(m_confirmPasswordEdit, &QLineEdit::textChanged, this, &ForgotPasswordWidget::onConfirmPasswordChanged);
    m_resetFormLayout->addRow("确认密码:", m_confirmPasswordEdit);

    m_confirmPasswordHintLabel = new QLabel(this);
    m_confirmPasswordHintLabel->setObjectName("hintLabel");
    m_confirmPasswordHintLabel->setWordWrap(true);
    m_resetFormLayout->addRow("", m_confirmPasswordHintLabel);

    // 显示密码选项
    m_showPasswordCheck = new QCheckBox("显示密码", this);
    m_showPasswordCheck->setObjectName("checkBox");
    connect(m_showPasswordCheck, &QCheckBox::toggled, 
            this, &ForgotPasswordWidget::onShowPasswordToggled);
    m_resetFormLayout->addRow("", m_showPasswordCheck);

    resetLayout->addWidget(m_resetGroup);

    // 按钮区域
    QVBoxLayout *resetButtonLayout = new QVBoxLayout();
    resetButtonLayout->setSpacing(10);

    m_resetPasswordButton = new QPushButton("重置密码", this);
    m_resetPasswordButton->setObjectName("primaryButton");
    m_resetPasswordButton->setDefault(true);
    connect(m_resetPasswordButton, &QPushButton::clicked, this, &ForgotPasswordWidget::onResetPasswordClicked);
    resetButtonLayout->addWidget(m_resetPasswordButton);

    QHBoxLayout *resetLinkLayout = new QHBoxLayout();
    
    QPushButton *backToEmailButton = new QPushButton("重新发送邮件", this);
    backToEmailButton->setObjectName("linkButton");
    connect(backToEmailButton, &QPushButton::clicked, this, &ForgotPasswordWidget::switchToEmailStep);
    resetLinkLayout->addWidget(backToEmailButton);

    resetLinkLayout->addStretch();

    m_backToLoginButton2 = new QPushButton("返回登录", this);
    m_backToLoginButton2->setObjectName("linkButton");
    connect(m_backToLoginButton2, &QPushButton::clicked, this, &ForgotPasswordWidget::onBackToLoginClicked);
    resetLinkLayout->addWidget(m_backToLoginButton2);

    resetButtonLayout->addLayout(resetLinkLayout);
    resetLayout->addLayout(resetButtonLayout);

    // 状态显示
    m_resetStatusLabel = new QLabel(this);
    m_resetStatusLabel->setAlignment(Qt::AlignCenter);
    m_resetStatusLabel->setObjectName("statusLabel");
    m_resetStatusLabel->setWordWrap(true);
    resetLayout->addWidget(m_resetStatusLabel);

    m_resetProgressBar = new QProgressBar(this);
    m_resetProgressBar->setVisible(false);
    m_resetProgressBar->setObjectName("progressBar");
    resetLayout->addWidget(m_resetProgressBar);

    m_stackedWidget->addWidget(m_resetPage);
}

void ForgotPasswordWidget::applyStyles()
{
    setStyleSheet(QString(R"(
        QWidget {
            background: qlineargradient(x1:0, y1:0, x2:1, y2:1,
                stop:0 %1, stop:0.5 #34495E, stop:1 #2C3E50);
            color: %2;
            font-family: 'Microsoft YaHei', 'Segoe UI', Arial, sans-serif;
        }

        #spacerWidget {
            background: transparent;
        }

        #forgotMainContainer {
            background: transparent;
        }

        #forgotCard {
            background: transparent;
        }

        #forgotFormContainer {
            background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                stop:0 rgba(44, 62, 80, 0.95), stop:1 rgba(52, 73, 94, 0.95));
            border-radius: 25px;
            /* 移除不支持的box-shadow属性 */
            border: 2px solid rgba(74, 144, 226, 0.6);
        }

        #forgotLogo {
            font-size: 30px;
            color: %3;
            /* 移除不支持的text-shadow属性 */
            background: qlineargradient(x1:0, y1:0, x2:1, y2:1,
                stop:0 rgba(74, 144, 226, 0.2), stop:1 rgba(52, 152, 219, 0.2));
            border-radius: 20px;
            border: 2px solid rgba(74, 144, 226, 0.4);
        }

        #forgotDecorIcon {
            font-size: 26px;
            color: #9B59B6;
            /* 移除不支持的text-shadow属性 */
            background: qlineargradient(x1:0, y1:0, x2:1, y2:1,
                stop:0 rgba(155, 89, 182, 0.2), stop:1 rgba(142, 68, 173, 0.2));
            border-radius: 20px;
            border: 2px solid rgba(155, 89, 182, 0.4);
        }

        #forgotTitle {
            color: %2;
            font-size: 21px;
            font-weight: bold;
            margin-bottom: 3px;
            /* 移除不支持的text-shadow属性 */
        }

        #forgotSubtitle {
            color: #BDC3C7;
            font-size: 13px;
            font-weight: 400;
            margin-bottom: 10px;
            line-height: 1.3;
        }

        #titleLabel {
            font-size: 28px;
            font-weight: bold;
            color: %3;
            margin-bottom: 10px;
            /* 移除不支持的text-shadow属性 */
        }

        #subtitleLabel {
            font-size: 16px;
            color: #BDC3C7;
            margin-bottom: 20px;
            font-weight: 300;
        }

        #instructionLabel {
            font-size: 14px;
            color: #BDC3C7;
            margin: 10px 0;
            line-height: 1.4;
        }

        #inputGroup {
            background-color: rgba(52, 73, 94, 0.8);
            border: 2px solid %3;
            border-radius: 10px;
            padding: 20px;
            margin: 10px;
        }

        #inputGroup::title {
            color: %3;
            font-size: 16px;
            font-weight: bold;
            padding: 0 10px;
        }

        #inputField {
            background-color: rgba(44, 62, 80, 0.9);
            border: 2px solid #34495E;
            border-radius: 8px;
            padding: 12px 15px;
            font-size: 14px;
            color: %2;
            min-height: 20px;
        }

        #inputField:focus {
            border-color: %3;
            background-color: rgba(52, 73, 94, 0.9);
        }

        #inputField:hover {
            border-color: #5DADE2;
        }

        #checkBox {
            color: %2;
            font-size: 13px;
        }

        #checkBox::indicator {
            width: 16px;
            height: 16px;
            border: 2px solid #34495E;
            border-radius: 3px;
            background-color: rgba(44, 62, 80, 0.9);
        }

        #checkBox::indicator:checked {
            background-color: %3;
            border-color: %3;
        }

        #primaryButton {
            background-color: %3;
            color: white;
            border: none;
            border-radius: 8px;
            padding: 15px 30px;
            font-size: 16px;
            font-weight: bold;
            min-height: 20px;
        }

        #primaryButton:hover {
            background-color: #5DADE2;
        }

        #primaryButton:disabled {
            background-color: #7F8C8D;
            color: #BDC3C7;
        }

        #linkButton {
            background-color: transparent;
            color: %3;
            border: none;
            font-size: 13px;
            text-decoration: underline;
            padding: 5px 10px;
        }

        #linkButton:hover {
            color: #5DADE2;
        }

        #hintLabel {
            font-size: 12px;
            margin-top: -5px;
            margin-bottom: 5px;
        }

        #statusLabel {
            font-size: 14px;
            padding: 10px;
            border-radius: 5px;
            margin: 5px 0;
        }

        #progressBar {
            border: 2px solid %3;
            border-radius: 5px;
            text-align: center;
            background-color: rgba(44, 62, 80, 0.9);
        }

        #progressBar::chunk {
            background-color: %3;
            border-radius: 3px;
        }

        QFormLayout QLabel {
            color: %2;
            font-size: 14px;
            font-weight: 500;
        }
    )").arg(m_backgroundColor, m_textColor, m_primaryColor));
}

void ForgotPasswordWidget::onSendResetEmailClicked()
{
    if (!validateEmail()) {
        return;
    }

    setUIEnabled(false);
    m_emailProgressBar->setVisible(true);
    m_emailStatusLabel->setText("正在发送重置邮件...");
    m_emailStatusLabel->setStyleSheet("color: #3498DB; background-color: rgba(52, 152, 219, 0.1);");

    m_authService->forgotPassword(m_emailEdit->text().trimmed());
}

void ForgotPasswordWidget::onResetPasswordClicked()
{
    if (!validateResetForm()) {
        return;
    }

    setUIEnabled(false);
    m_resetProgressBar->setVisible(true);
    m_resetStatusLabel->setText("正在重置密码...");
    m_resetStatusLabel->setStyleSheet("color: #3498DB; background-color: rgba(52, 152, 219, 0.1);");

    m_authService->resetPassword(m_tokenEdit->text().trimmed(), m_newPasswordEdit->text());
}

void ForgotPasswordWidget::onBackToLoginClicked()
{
    clearForm();
    emit switchToLogin();
}

void ForgotPasswordWidget::onForgotPasswordSucceeded()
{
    setUIEnabled(true);
    m_emailProgressBar->setVisible(false);
    m_emailStatusLabel->setText("重置邮件已发送! 请检查您的邮箱");
    m_emailStatusLabel->setStyleSheet(QString("color: %1; background-color: rgba(39, 174, 96, 0.1);").arg(m_successColor));

    // 自动切换到重置密码页面
    QTimer::singleShot(2000, this, &ForgotPasswordWidget::switchToResetStep);
}

void ForgotPasswordWidget::onForgotPasswordFailed(const QString &error)
{
    setUIEnabled(true);
    m_emailProgressBar->setVisible(false);
    m_emailStatusLabel->setText(error);
    m_emailStatusLabel->setStyleSheet(QString("color: %1; background-color: rgba(231, 76, 60, 0.1);").arg(m_errorColor));
}

void ForgotPasswordWidget::onResetPasswordSucceeded()
{
    setUIEnabled(true);
    m_resetProgressBar->setVisible(false);
    m_resetStatusLabel->setText("密码重置成功! 请使用新密码登录");
    m_resetStatusLabel->setStyleSheet(QString("color: %1; background-color: rgba(39, 174, 96, 0.1);").arg(m_successColor));

    clearForm();

    // 延迟切换到登录页面
    QTimer::singleShot(2000, this, &ForgotPasswordWidget::switchToLogin);
}

void ForgotPasswordWidget::onResetPasswordFailed(const QString &error)
{
    setUIEnabled(true);
    m_resetProgressBar->setVisible(false);
    m_resetStatusLabel->setText(error);
    m_resetStatusLabel->setStyleSheet(QString("color: %1; background-color: rgba(231, 76, 60, 0.1);").arg(m_errorColor));
}

void ForgotPasswordWidget::onEmailChanged()
{
    QString email = m_emailEdit->text();

    if (email.isEmpty()) {
        m_emailHintLabel->clear();
        return;
    }

    if (isValidEmail(email)) {
        m_emailHintLabel->setText("✓ 邮箱格式正确");
        m_emailHintLabel->setStyleSheet(QString("color: %1;").arg(m_successColor));
    } else {
        m_emailHintLabel->setText("✗ 请输入有效的邮箱地址");
        m_emailHintLabel->setStyleSheet(QString("color: %1;").arg(m_errorColor));
    }
}

void ForgotPasswordWidget::onTokenChanged()
{
    QString token = m_tokenEdit->text();

    if (token.isEmpty()) {
        m_tokenHintLabel->clear();
        return;
    }

    if (token.length() >= 6) {
        m_tokenHintLabel->setText("✓ 令牌格式正确");
        m_tokenHintLabel->setStyleSheet(QString("color: %1;").arg(m_successColor));
    } else {
        m_tokenHintLabel->setText("✗ 令牌长度不足");
        m_tokenHintLabel->setStyleSheet(QString("color: %1;").arg(m_errorColor));
    }
}

void ForgotPasswordWidget::onPasswordChanged()
{
    QString password = m_newPasswordEdit->text();

    if (password.isEmpty()) {
        m_passwordHintLabel->clear();
        return;
    }

    if (isValidPassword(password)) {
        m_passwordHintLabel->setText("✓ 密码格式正确");
        m_passwordHintLabel->setStyleSheet(QString("color: %1;").arg(m_successColor));
    } else {
        m_passwordHintLabel->setText("✗ 密码必须至少8个字符，包含字母和数字");
        m_passwordHintLabel->setStyleSheet(QString("color: %1;").arg(m_errorColor));
    }

    onConfirmPasswordChanged(); // 重新验证确认密码
}

void ForgotPasswordWidget::onConfirmPasswordChanged()
{
    QString password = m_newPasswordEdit->text();
    QString confirmPassword = m_confirmPasswordEdit->text();

    if (confirmPassword.isEmpty()) {
        m_confirmPasswordHintLabel->clear();
        return;
    }

    if (password == confirmPassword) {
        m_confirmPasswordHintLabel->setText("✓ 密码匹配");
        m_confirmPasswordHintLabel->setStyleSheet(QString("color: %1;").arg(m_successColor));
    } else {
        m_confirmPasswordHintLabel->setText("✗ 密码不匹配");
        m_confirmPasswordHintLabel->setStyleSheet(QString("color: %1;").arg(m_errorColor));
    }
}

void ForgotPasswordWidget::onShowPasswordToggled(bool show)
{
    QLineEdit::EchoMode mode = show ? QLineEdit::Normal : QLineEdit::Password;
    m_newPasswordEdit->setEchoMode(mode);
    m_confirmPasswordEdit->setEchoMode(mode);
}

bool ForgotPasswordWidget::validateEmail()
{
    QString email = m_emailEdit->text().trimmed();

    if (email.isEmpty()) {
        m_emailStatusLabel->setText("请输入邮箱地址");
        m_emailStatusLabel->setStyleSheet(QString("color: %1; background-color: rgba(231, 76, 60, 0.1);").arg(m_errorColor));
        m_emailEdit->setFocus();
        return false;
    }

    if (!isValidEmail(email)) {
        m_emailStatusLabel->setText("邮箱格式不正确");
        m_emailStatusLabel->setStyleSheet(QString("color: %1; background-color: rgba(231, 76, 60, 0.1);").arg(m_errorColor));
        m_emailEdit->setFocus();
        return false;
    }

    return true;
}

bool ForgotPasswordWidget::validateResetForm()
{
    QString token = m_tokenEdit->text().trimmed();
    QString password = m_newPasswordEdit->text();
    QString confirmPassword = m_confirmPasswordEdit->text();

    if (token.isEmpty()) {
        m_resetStatusLabel->setText("请输入重置令牌");
        m_resetStatusLabel->setStyleSheet(QString("color: %1; background-color: rgba(231, 76, 60, 0.1);").arg(m_errorColor));
        m_tokenEdit->setFocus();
        return false;
    }

    if (token.length() < 6) {
        m_resetStatusLabel->setText("重置令牌格式不正确");
        m_resetStatusLabel->setStyleSheet(QString("color: %1; background-color: rgba(231, 76, 60, 0.1);").arg(m_errorColor));
        m_tokenEdit->setFocus();
        return false;
    }

    if (password.isEmpty()) {
        m_resetStatusLabel->setText("请输入新密码");
        m_resetStatusLabel->setStyleSheet(QString("color: %1; background-color: rgba(231, 76, 60, 0.1);").arg(m_errorColor));
        m_newPasswordEdit->setFocus();
        return false;
    }

    if (!isValidPassword(password)) {
        m_resetStatusLabel->setText("密码格式不正确");
        m_resetStatusLabel->setStyleSheet(QString("color: %1; background-color: rgba(231, 76, 60, 0.1);").arg(m_errorColor));
        m_newPasswordEdit->setFocus();
        return false;
    }

    if (password != confirmPassword) {
        m_resetStatusLabel->setText("两次输入的密码不一致");
        m_resetStatusLabel->setStyleSheet(QString("color: %1; background-color: rgba(231, 76, 60, 0.1);").arg(m_errorColor));
        m_confirmPasswordEdit->setFocus();
        return false;
    }

    return true;
}

bool ForgotPasswordWidget::isValidEmail(const QString &email)
{
    QRegularExpression emailRegex(R"(^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$)");
    return emailRegex.match(email).hasMatch();
}

bool ForgotPasswordWidget::isValidPassword(const QString &password)
{
    if (password.length() < 8) {
        return false;
    }

    // 检查是否包含字母和数字
    bool hasLetter = false;
    bool hasDigit = false;

    for (const QChar &ch : password) {
        if (ch.isLetter()) {
            hasLetter = true;
        } else if (ch.isDigit()) {
            hasDigit = true;
        }
    }

    return hasLetter && hasDigit;
}

void ForgotPasswordWidget::switchToResetStep()
{
    m_stackedWidget->setCurrentWidget(m_resetPage);
    m_tokenEdit->setFocus();
}

void ForgotPasswordWidget::switchToEmailStep()
{
    m_stackedWidget->setCurrentWidget(m_emailPage);
    m_emailEdit->setFocus();
}

void ForgotPasswordWidget::setUIEnabled(bool enabled)
{
    // 邮箱页面控件
    m_emailEdit->setEnabled(enabled);
    m_sendEmailButton->setEnabled(enabled);
    m_backToLoginButton1->setEnabled(enabled);

    // 重置密码页面控件
    m_tokenEdit->setEnabled(enabled);
    m_newPasswordEdit->setEnabled(enabled);
    m_confirmPasswordEdit->setEnabled(enabled);
    m_showPasswordCheck->setEnabled(enabled);
    m_resetPasswordButton->setEnabled(enabled);
    m_backToLoginButton2->setEnabled(enabled);
}

void ForgotPasswordWidget::clearForm()
{
    // 清空邮箱页面
    m_emailEdit->clear();
    m_emailHintLabel->clear();
    m_emailStatusLabel->clear();
    m_emailProgressBar->setVisible(false);

    // 清空重置密码页面
    m_tokenEdit->clear();
    m_newPasswordEdit->clear();
    m_confirmPasswordEdit->clear();
    m_showPasswordCheck->setChecked(false);
    m_tokenHintLabel->clear();
    m_passwordHintLabel->clear();
    m_confirmPasswordHintLabel->clear();
    m_resetStatusLabel->clear();
    m_resetProgressBar->setVisible(false);

    // 切换到邮箱页面
    switchToEmailStep();
}
